<template>
  <div class="content-box" style="background-color: #fff">
    <div style="margin-bottom: 10px">
      <h3 align="center">{{ head }}</h3>
      <h3 align="center">
        <hr
          style="
            width: 150px;
            border: none;
            border-top: 6px solid #606266;
            margin-bottom: 3px;
          "
        />
        <hr style="width: 150px; border: none; border-top: 2px solid #606266" />
      </h3>
    </div>
    <div class="container">
      <div class="container1">
        <div>
          <!-- 项目基本信息 -->
          <div style="width: 100%; height: 30px; background-color: #fafafa">
            <!-- 隐藏按钮 -->
            <el-button
              v-if="isDisplay == true"
              icon="el-icon-arrow-up"
              @click="changeDisplay()"
              circle
              size="mini"
              style="color: #7aaafd"
            ></el-button>
            <el-button
              v-else
              @click="changeDisplay()"
              icon="el-icon-arrow-down"
              circle
              size="mini"
              style="color: #7aaafd"
            ></el-button>
            &nbsp;项目基本信息
          </div>
          <div v-show="isDisplay">
            <el-form
              label-width="180px"
              size="mini"
              :label-position="labelPosition"
              style="margin-top: 60px"
              :rules="saveRules"
              :model="saveForm"
              :inline="true"
              ref="saveForm"
            >
              <el-form-item label="项目" prop="projectId">
                <el-select v-model="saveForm.projectId" style="width: 218px">
                  <el-option
                    v-for="item in projectList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="项目编号">
                <el-input
                  v-model="saveForm.projectNumber"
                  style="width: 220px"
                ></el-input>
              </el-form-item>
              <el-form-item label="立项日期" prop="projectApprovalDate">
                <el-date-picker
                  v-model="saveForm.projectApprovalDate"
                  align="right"
                  type="date"
                  placeholder="选择日期"
                  :picker-options="pickerOptions"
                ></el-date-picker>
              </el-form-item>
              <el-form-item
                label="预计开工日期"
                prop="expectedCommencementDate"
              >
                <el-date-picker
                  v-model="saveForm.expectedCommencementDate"
                  class="he-wh-200-40"
                  type="date"
                  align="right"
                  placeholder="选择日期"
                  :picker-options="pickerOptions"
                ></el-date-picker>
              </el-form-item>
              <el-form-item label="预计完工日期" prop="estimatedCompletionDate">
                <el-date-picker
                  v-model="saveForm.estimatedCompletionDate"
                  style="width: 218px"
                  type="date"
                  align="right"
                  placeholder="选择日期"
                  :picker-options="pickerOptions"
                ></el-date-picker>
              </el-form-item>
              <el-form-item
                label="预计总工期(自动计算)"
                prop="totalConstructionPeriod"
              >
                <el-input
                  v-model="saveForm.totalConstructionPeriod"
                  :disabled="true"
                  style="width: 220px"
                ></el-input>
              </el-form-item>
              <el-form-item label="质量等级">
                <el-input
                  v-model="saveForm.qualityGrade"
                  style="width: 220px"
                ></el-input>
              </el-form-item>
              <el-form-item label="建设单位" prop="unitOfConstruction">
                <el-select
                  v-model="saveForm.unitOfConstruction"
                  style="width: 218px"
                >
                  <el-option
                    v-for="item in unitOfConstructionList"
                    :key="item.contactId"
                    :label="item.contactName"
                    :value="item.contactId"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="施工单位" prop="constructionUnit">
                <el-select
                  v-model="saveForm.constructionUnit"
                  style="width: 218px"
                >
                  <el-option
                    v-for="item in constructionUnitList"
                    :key="item.contactId"
                    :label="item.contactName"
                    :value="item.contactId"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="监理单位" prop="constructionControlUnit">
                <el-select
                  v-model="saveForm.constructionControlUnit"
                  style="width: 218px"
                >
                  <el-option
                    class="he-wh-200-40"
                    v-for="item in constructionControlUnitList"
                    :key="item.contactId"
                    :label="item.contactName"
                    :value="item.contactId"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="设计单位" prop="designUnit">
                <el-select v-model="saveForm.designUnit" style="width: 218px">
                  <el-option
                    v-for="item in designUnitList"
                    :key="item.contactId"
                    :label="item.contactName"
                    :value="item.contactId"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="立项负责人" prop="inCharge">
                <el-select v-model="saveForm.inCharge" style="width: 218px">
                  <el-option
                    v-for="item in inChargeList"
                    :key="item.id"
                    :label="item.userName"
                    :value="item.id"
                  ></el-option>
                </el-select> </el-form-item
              ><br />
              <el-form-item label="项目地址">
                <el-input
                  v-model="saveForm.projectAddress"
                  style="width: 220px"
                ></el-input> </el-form-item
              ><br />
              <el-form-item label="项目说明">
                <el-input
                  type="textarea"
                  :rows="3"
                  style="width: 800px"
                  v-model="saveForm.projectIllustrate"
                ></el-input>
              </el-form-item>
            </el-form>
          </div>
          <!-- 项目组成员 -->
          <div style="width: 100%; height: 30px; background-color: #fafafa">
            <!-- 隐藏按钮 -->
            <el-button
              v-if="isDisplayUser == true"
              icon="el-icon-arrow-up"
              @click="changeDisplayUser()"
              circle
              size="mini"
              style="color: #7aaafd"
            ></el-button>
            <el-button
              v-else
              @click="changeDisplayUser()"
              icon="el-icon-arrow-down"
              circle
              size="mini"
              style="color: #7aaafd"
            ></el-button>
            &nbsp;项目组成员
          </div>
          <div v-show="isDisplayUser">
            <el-button @click="openVisible()">新增</el-button>
            <el-table
              :data="tableData"
              border
              height="300"
              style="width: 100%; font-size: 12px; margin-top: 10px"
              :cell-style="cellStyle"
              :header-cell-style="rowClass"
              :show-overflow-tooltip="true"
            >
              <el-table-column
                label="项目角色"
                align="center"
                prop="projectRole"
              ></el-table-column
              ><el-table-column
                label="人员"
                align="center"
                prop="userName"
              ></el-table-column
              ><el-table-column
                label="备注"
                align="center"
                prop="remark"
              ></el-table-column>
            </el-table>
          </div>
          <!-- 附件 -->
          <div>
            <div style="width: 100%; height: 30px; background-color: #fafafa">
              <!-- 隐藏按钮 -->
              <el-button
                v-if="isDisplayFile == true"
                icon="el-icon-arrow-up"
                @click="changeDisplayFile()"
                circle
                size="mini"
                style="color: #7aaafd"
              ></el-button>
              <el-button
                v-else
                @click="changeDisplayFile()"
                icon="el-icon-arrow-down"
                circle
                size="mini"
                style="color: #7aaafd"
              ></el-button>
              &nbsp;附件上传
            </div>
            <div v-show="isDisplayFile">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                >上传</el-button
              >
              <el-table
                :data="attachments"
                border
                height="300"
                style="width: 100%; font-size: 12px; margin-top: 10px"
                :cell-style="cellStyle"
                :header-cell-style="rowClass"
                :show-overflow-tooltip="true"
              >
                <el-table-column
                  label="文件名称"
                  align="center"
                  prop="fileName"
                ></el-table-column>
                <el-table-column
                  label="文件类型"
                  align="center"
                  prop="fileType"
                ></el-table-column>
                <el-table-column
                  label="文件大小(MB)"
                  align="center"
                  prop="fileSize"
                ></el-table-column>
                <el-table-column label="状态" align="center">
                  <template slot-scope="scope">
                    <span v-if="scope.row.state == 0">上传成功</span>
                    <span v-if="scope.row.state == 1">待提交</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                  <teleport slot-scope="scope">
                    <template>
                      <show v-if="head === '修改项目'">
                        <el-button
                          type="primary"
                          plain
                          icon="el-icon-download"
                          size="mini"
                          @click="download(scope.row)"
                          >下载</el-button
                        >
                      </show>
                      <el-button
                        type="primary"
                        plain
                        icon="el-icon-delete"
                        size="mini"
                        @click="deleteFile(scope.$index, scope.row)"
                        >删除</el-button
                      >
                    </template>
                  </teleport>
                </el-table-column>
              </el-table>
            </div>
            <file-upload
              ref="fileUploadDialog"
              @input="getAttachList"
            ></file-upload>
          </div>
        </div>
        <!-- 项目组 成语添加弹窗 -->
        <div>
          <sys-dialog
            :title="title"
            :visible="visible"
            :width="1300"
            :height="500"
            @onClose="detailsDialogClose"
            @onConfirm="detailsDialogConfirm"
          >
            <div slot="content">
              <el-form
                label-width="180px"
                size="mini"
                :label-position="labelPosition"
                style="margin-top: 60px"
              >
                <el-form-item label="项目角色">
                  <el-input
                    style="width: 220px"
                    v-model="saveUser.projectRole"
                  ></el-input>
                </el-form-item>
                <el-form-item label="人员">
                  <el-select style="width: 218px" v-model="saveUser.userId">
                    <el-option
                      v-for="item in inChargeList"
                      :key="item.id"
                      :label="item.userName"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="备注">
                  <el-input
                    style="width: 220px"
                    v-model="saveUser.remark"
                  ></el-input>
                </el-form-item>
              </el-form>
            </div>
          </sys-dialog>
        </div>
      </div>
    </div>
    <div style="text-align: center">
      <!-- 返回上一个页面 -->
      <el-button @click="back()" size="mini">取 消</el-button>
      <el-button type="primary" @click="trueAdd()" size="mini">确 定</el-button>
    </div>
  </div>
</template>

<script>
import sysDialog from "@/components/common/sysDialog.vue"; // 弹窗
import FileUpload from "@/components/common/fileUpload.vue"; // 附件上传
import request from "@/util/request";
import axios from "axios";
const saveUser = {
  // 保存用户
  projectRole: "", // 项目角色
  userName: "", // 人员
  userId: "", //人员id
  remark: "", // 备注
};

const saveForm = {
  // 保存表单
  projectId: "", // 项目
  projectNumber: "", // 项目编号
  projectApprovalDate: "", // 立项日期
  expectedCommencementDate: "", // 预计开工日期
  estimatedCompletionDate: "", // 预计完工日期
  totalConstructionPeriod: "", // 预计总工期
  qualityGrade: "", // 质量等级
  unitOfConstruction: "", // 建设单位
  constructionUnit: "", // 施工单位
  constructionControlUnit: "", // 监理单位
  designUnit: "", // 设计单位
  inCharge: "", // 立项负责人
  projectAddress: "", // 项目地址
  projectIllustrate: "", // 项目说明
};
const saveRules = {
  // 验证规则
  projectId: [{ required: true, message: "请选择项目", trigger: "change" }],
  projectApprovalDate: [
    { required: true, message: "请选择立项日期", trigger: "blur" },
  ],
  expectedCommencementDate: [
    { required: true, message: "请选择预计开工日期", trigger: "blur" },
  ],
  estimatedCompletionDate: [
    { required: true, message: "请选择预计完工日期", trigger: "blur" },
  ],
  totalConstructionPeriod: [
    { required: true, message: "请输入预计总工期", trigger: "blur" },
  ],
  qualityGrade: [
    { required: true, message: "请输入质量等级", trigger: "blur" },
  ],
  unitOfConstruction: [
    { required: true, message: "请选择建设单位", trigger: "blur" },
  ],
  constructionUnit: [
    { required: true, message: "请选择施工单位", trigger: "blur" },
  ],
  constructionControlUnit: [
    { required: true, message: "请选择监理单位", trigger: "blur" },
  ],
  designUnit: [{ required: true, message: "请选择设计单位", trigger: "blur" }],
  inCharge: [{ required: true, message: "请选择立项负责人", trigger: "blur" }],
};
const pickerOptions = {
  // 时间选择器
  disabledDate(time) {
    return time.getTime() > Date.now();
  },
  shortcuts: [
    {
      text: "今天",
      onClick(picker) {
        picker.$emit("pick", new Date());
      },
    },
    {
      text: "昨天",
      onClick(picker) {
        const date = new Date();
        date.setTime(date.getTime() - 3600 * 1000 * 24);
        picker.$emit("pick", date);
      },
    },
    {
      text: "一周前",
      onClick(picker) {
        const date = new Date();
        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
        picker.$emit("pick", date);
      },
    },
  ],
  disabledDate(time) {
    const dateTime = new Date();
    const startDateTime = dateTime.setDate(dateTime.getDate() - 1);
    const endDateTime = dateTime.setDate(dateTime.getDate() + 30000); //30000为当前日期之后多少天
    return (
      time.getTime() < new Date(startDateTime).getTime() ||
      time.getTime() > new Date(endDateTime).getTime()
    );
  },
};
export default {
  name: "projectApprovalAU",
  components: {
    sysDialog,
    FileUpload,
  },
  data() {
    return {
      head: "", // 标题
      row: {}, // 传过来的数据
      isDisplay: true, // 是否显示
      labelPosition: "right", // label的位置
      saveForm: Object.assign({}, saveForm), // 保存表单
      saveRules: Object.assign({}, saveRules), // 验证规则
      pickerOptions: Object.assign({}, pickerOptions), // 时间选择器
      projectList: [], // 项目列表
      unitOfConstructionList: [], // 建设单位列表
      constructionUnitList: [], // 施工单位列表
      constructionControlUnitList: [], // 监理单位列表
      designUnitList: [], // 设计单位列表
      inChargeList: [], // 立项负责人列表
      isDisplayUser: true, // 是否显示
      saveUser: Object.assign({}, saveUser), // 保存用户
      tableData: [], // 项目组成员
      title: "项目组成员添加", // 弹窗标题
      visible: false, // 弹窗是否显示
      attachments: [], //附件
      fileList: [], //附件列表
      isDisplayFile: true, // 是否显示
      ye: false,
    };
  },
  watch: {
    ye: function () {
      if (this.ye) {
        this.$router.push("/projectApproval");
      }
    },
    // 监听时间
    "saveForm.expectedCommencementDate": function () {
      this.wathTime();
    },
    "saveForm.estimatedCompletionDate": function () {
      this.wathTime();
    },
  },
  created() {
    //页面刷新跳转上一页
    window.addEventListener("beforeunload", this.handleBeforeunload);
  },
  beforeDestroy() {
    //页面刷新跳转上一页
    window.removeEventListener("beforeunload", this.handleBeforeunload);
  },
  mounted() {
    this.activated();
    this.fakeData();
  },
  methods: {
    fakeData() {
      // 假数据
      // 项目列表
      this.projectList = [
        {
          id: 1,
          name: "项目1",
        },
        {
          id: 2,
          name: "项目2",
        },
        {
          id: 3,
          name: "项目3",
        },
      ];
      // 建设单位列表
      this.unitOfConstructionList = [
        {
          contactId: "1",
          contactName: "建设单位1",
        },
        {
          contactId: "2",
          contactName: "建设单位2",
        },
        {
          contactId: "3",
          contactName: "建设单位3",
        },
      ];
      // 施工单位列表
      this.constructionUnitList = [
        {
          contactId: "1",
          contactName: "施工单位1",
        },
        {
          contactId: "2",
          contactName: "施工单位2",
        },
        {
          contactId: "3",
          contactName: "施工单位3",
        },
      ];
      // 监理单位列表
      this.constructionControlUnitList = [
        {
          contactId: "1",
          contactName: "监理单位1",
        },
        {
          contactId: "2",
          contactName: "监理单位2",
        },
        {
          contactId: "3",
          contactName: "监理单位3",
        },
      ];
      // 设计单位列表
      this.designUnitList = [
        {
          contactId: "1",
          contactName: "设计单位1",
        },
        {
          contactId: "2",
          contactName: "设计单位2",
        },
        {
          contactId: "3",
          contactName: "设计单位3",
        },
      ];
      // 立项负责人列表
      this.inChargeList = [
        {
          id: 1,
          userName: "立项负责人1",
        },
        {
          id: 2,
          userName: "立项负责人2",
        },
        {
          id: 3,
          userName: "立项负责人3",
        },
      ];
    },
    //  保存
    async trueAdd() {
      //文件非空判断
      let d = [];
      let params = {};
      if (this.fileList.length != 0) {
        const res = await this.$refs.fileUploadDialog.submit(
          this.fileList,
          "project-approval"
        );
        d = res;
        if (d.length == 0) {
          this.$message({
            message: "文件上传失败",
            type: "warning",
          });
          return;
        }
        if (this.$route.params.type === "update") {
          // 循环将文件内容添加到附件id组中 d为附件id组
          for (let i = 0; i < this.attachments.length; i++) {
            d.push(this.attachments[i].id);
          }
        }
        params["fileIds"] = d;
      }
      // 保存
      params["projectId"] = this.saveForm.projectId;
      params["projectNumber"] = this.saveForm.projectNumber;
      params["projectApprovalDate"] = this.saveForm.projectApprovalDate;
      params["expectedCommencementDate"] =
        this.saveForm.expectedCommencementDate;
      params["estimatedCompletionDate"] = this.saveForm.estimatedCompletionDate;
      params["totalConstructionPeriod"] = this.saveForm.totalConstructionPeriod;
      params["qualityGrade"] = this.saveForm.qualityGrade;
      params["unitOfConstruction"] = this.saveForm.unitOfConstruction;
      params["constructionUnit"] = this.saveForm.constructionUnit;
      params["constructionControlUnit"] = this.saveForm.constructionControlUnit;
      params["designUnit"] = this.saveForm.designUnit;
      params["inCharge"] = this.saveForm.inCharge;
      params["projectAddress"] = this.saveForm.projectAddress;
      params["projectIllustrate"] = this.saveForm.projectIllustrate;
      params["membersList"] = this.tableData;
      let url = "/project-approval/save";
      if (this.$route.params.type === "update") {
        url = "/project-approval/update";
        params["id"] = this.saveForm.id;
      }
      request.post(url, params).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: "成功",
            type: "success",
            duration: 1500,
          });
          //延迟1.5秒返回上一个页面
          setTimeout(() => {
            this.back();
          }, 1500);
        } else {
          this.$message({
            message: "失败",
            type: "warning",
          });
        }
      });
    },
    download(row) {
      // 下载
      window.open(row.filePath);
    },
    deleteFile(index, row) {
      // 删除文件
      if (this.$route.params.type === "update") {
        //  删除数据库中的文件
        let t = [];
        t.push(row.id);
        request.post("/file/deleteFile", { ids: t }).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: "删除成功",
              type: "success",
            });
          } else {
            this.$message({
              message: "删除失败",
              type: "warning",
            });
            return;
          }
        });
      }
      this.fileList.splice(index, 1);
      this.attachments.splice(index, 1);
    },
    handleAdd() {
      // 上传
      this.$refs.fileUploadDialog.show();
    },
    getAttachList(attachments, fileList) {
      //  获取附件信息列表
      this.attachments.push(...attachments);

      // 附件列表
      this.fileList.push(...fileList);
      console.log(this.fileList);
    },
    changeDisplayFile() {
      // 改变显示状态
      this.isDisplayFile = !this.isDisplayFile;
    },
    openVisible() {
      // 打开弹窗
      this.visible = true;
    },
    detailsDialogConfirm() {
      // 弹窗确定
      this.tableData.push(this.saveUser);
      this.saveUser = Object.assign({}, saveUser);
      this.visible = false;
    },
    detailsDialogClose() {
      // 弹窗关闭
      this.saveUser = Object.assign({}, saveUser);
      this.visible = false;
    },
    wathTime() {
      // 监听时间
      if (
        this.saveForm.expectedCommencementDate != "" &&
        this.saveForm.estimatedCompletionDate != ""
      ) {
        if (
          this.saveForm.expectedCommencementDate >
          this.saveForm.estimatedCompletionDate
        ) {
          this.$message({
            message: "预计开工日期不能大于预计完工日期",
            type: "warning",
          });
          this.saveForm.estimatedCompletionDate = "";
          return;
        }
        var date1 = new Date(this.saveForm.expectedCommencementDate);
        var date2 = new Date(this.saveForm.estimatedCompletionDate);
        var date3 = date2.getTime() - date1.getTime(); //时间差的毫秒数
        //计算出相差天数
        var days = Math.floor(date3 / (24 * 3600 * 1000));
        this.saveForm.totalConstructionPeriod = days;
      } else {
        this.saveForm.totalConstructionPeriod = "";
      }
    },
    changeDisplayUser() {
      // 改变显示状态
      this.isDisplayUser = !this.isDisplayUser;
    },
    // 改变显示状态
    changeDisplay() {
      this.isDisplay = !this.isDisplay;
    },
    async activated() {
      // 获取数据
      if (this.$route.params.type === "add") {
        this.head = "新建项目";
      } else if (this.$route.params.type === "update") {
        this.head = "修改项目";
        this.saveForm = this.$route.params.row;
        console.log(this.saveForm);
        // 获取项目组成员
        await request
          .get("/project-approval/getMembersList", {
            params: {
              constructionId: this.saveForm.id,
            },
          })
          .then((res) => {
            if (res.code == 200) {
              this.tableData = res.data;
            }
          });
        // 获取附件信息列表
        await request
          .get("/file/getFileList", {
            params: {
              tableId: this.saveForm.id,
              model: "project-approval",
            },
          })
          .then((res) => {
            if (res.code == 200) {
              this.attachments = res.data;
            }
          });
      }
    },
    handleBeforeunload(even) {
      //页面刷新 提示是否刷新 点击确定离开  刷新页面 去到 上一页
      this.back();
    },
    back() {
      //清空所有数据
      this.saveForm = Object.assign({}, saveForm);
      this.saveUser = Object.assign({}, saveUser);
      this.tableData = [];
      this.attachments = [];
      this.fileList = [];
      // 返回上一个页面
      this.$router.go(-1);
    },
    cellStyle() {
      //表格行居中
      return "text-align:center";
    },
    rowClass() {
      //表格列居中
      return "text-align:center";
    },
  },
};
</script>

<style>
.container1 {
  overflow-x: initial;
  overflow-y: auto;
  height: 700px;
}
</style>